//
//  ViewController.swift
//  Timer
//
//  Created by 李煜 on 2023/3/22.
//

import UIKit

class ViewController: UIViewController {
  var repeatTimer: Timer?
  var count: Int = 0
  var noRepeatTimer: Timer?
  var paramTimer: Timer?
  override func viewDidLoad() {
    super.viewDidLoad()

    // 重复执行定时器
    repeatTimer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(handleTimerExecution), userInfo: nil, repeats: true)
    // 执行一次的定时器
    noRepeatTimer = Timer.scheduledTimer(withTimeInterval: 1, repeats: false, block: { _ in
      print("timer 不重复执行的定时器.")
    })

    let userInfo: [String: Any] = ["name": "张三"]
    // 使用定时器[userInfo参数]传送消息
    paramTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(userInfoAction), userInfo: userInfo, repeats: false)
  }


  /// 停止一个重复执行的定时器,在count是5次的时候.
  /// 定时器所占用的内存不会被invalidate()方法立即释放。它将在系统认为合适的时候被释放。
  @objc private func handleTimerExecution() {
    print("timer has executed")
    if count == 5 {
      repeatTimer?.invalidate()
    }else{
      count += 1
    }
  }

  @objc private func userInfoAction(_ timer: Timer) {
    if let userInfo = timer.userInfo as? [String: Any] {
      print("user info is : \(userInfo)")
      paramTimer?.invalidate()
    }
  }
}
